<template>
  <div>
    <div id="proMap">
      <div id="mouse-position" class="mouse-position"></div><!--鼠标坐标信息-->
      <MapSource ref="bottomMapSource" class="layer-switch" :map="map" v-if="mmConfig.mcShow.mapSourceLoad===true"></MapSource>
<!--      <DrawPlotting ref="drawPlotting" v-if="mcShow.drawPlotting==='drawPlotting'"-->
<!--                    :plotConfig="{map:map,overSource:overSource,mcShow:mcShow}"-->
<!--      ></DrawPlotting>-->
      <div class="catalog-div" v-show="mcShow.catalog">
<!--        <Catalog :map="map" :mapRegion="mmConfig.mapRegion" :projectShowDatas="config.projectLayerTreeData"></Catalog>-->
      </div>
    </div>
<!--    <div ref="mapBtns" class="map-btns">-->
<!--      <div class="map-btn" title="定位" v-show="mcShow.loPosition">-->
<!--        <i class="wyicon-dingwei1" type="localPosition" title="定位" @click="ChangeMenuCss"></i><label>定位</label>-->
<!--        <div v-show="showBtn.rightbtns==='localPosition'" class="localPosition-popup">-->
<!--          <div><span class="coordinateX">x：</span><span type="lon"><input type="text"-->
<!--                                                                          ref="lp_coordinateX_text"-->
<!--          /></span></div>-->
<!--          <div><span class="coordinateY">y：</span><span type="lat"><input type="text"-->
<!--                                                                          ref="lp_coordinateY_text"-->
<!--          /></span></div>-->
<!--          <span type="position" title="定位" @click="localPositionClickSpan">定位</span>-->
<!--          <span type="position" title="取消" @click="localPositionCloseSpan">取消</span>-->
<!--        </div>-->
<!--      </div>-->
<!--      <div class="map-btn" type="measure" title="测量"-->
<!--           v-show="setVisible([showBtn.measureLength,showBtn.measureArea,showBtn.drawPlotting])"-->
<!--           @click="ChangeMenuCss"-->
<!--      >-->
<!--        <i class="title-btn wyicon-icon_measureTool"></i>-->
<!--        <div class="sub-menu" v-show="showBtn.rightbtns==='measure'">-->
<!--          <div class="map-btn " type="measureLength" title="量距" v-show="showBtn.measureLength"-->
<!--               @click="mapBtnIClick"-->
<!--          >-->
<!--            <i class="wyicon-celiang"></i><label>量距</label>-->
<!--          </div>-->
<!--          <div class="map-btn " type="measureArea" title="量面积" v-show="showBtn.measureArea" @click="mapBtnIClick">-->
<!--            <i class="wyicon-map-area"></i><label>面积</label>-->
<!--          </div>-->
<!--          <div class="map-btn" type="drawPlotting" title="标绘" v-show="showBtn.drawPlotting" @click="mapBtnIClick">-->
<!--            <i class="wyicon-shuqian"></i><label>标绘</label>-->
<!--          </div>-->
<!--        </div>-->
<!--        <label>测量</label>-->
<!--      </div>-->
<!--      <div class="map-btn" type="clearSelected" title="清除" v-show="showBtn.clearSelected"-->
<!--           @click="mapBtnIClick($event),ChangeMenuCss($event)"-->
<!--      >-->
<!--        <i class="wyicon-clean"></i><label>清除</label>-->
<!--      </div>-->
<!--    </div>-->
  </div>
</template>

<script>
import MapSource from '@/components/Map/MapSource'
import globalmf from '@/utils/Global/GlobalMapFunction'
import axios from 'axios'
import Bus from '@/utils/bus'
import { RegionSelects } from 'v-region'
import DrawPlotting from '@/components/Map/DrawPlotting'
import Catalog from '@/views/business/gbzcb/Catalog'
import AnalysisStatistic from '@/views/business/gbzcb/AnalysisStatistic'

export default {
  name: 'mapComp',
  components: { MapSource, RegionSelects, Catalog,DrawPlotting },
  data() {
    return {
      divType: {
        redline: 'redline',
        waterprotect: 'waterprotect',
        landspace: 'landspace'
      },
      fileList: [],
      map: null,
      viewNow: null,
      overSource: null,
      overVector: null,
      prj: null,
      prjCode: '4490',
      prjCodeStr: 'EPSG:4490',
      sketch: null,
      measure: null,
      snap: null, //捕捉
      measureTooltipElement: null,
      measureTooltip: null,
      analysisLayerType: '',
      analysisLayer: null,
      analysisLayers: [],
      analysisDraw: null,
      drawFeatures: [],
      attributeTable: {},

      x2js: null,
      activeName: 'basic-pro',
      project: {
        feature: null
      },
      config: {
        regionDatasourceName: null,
        regionDatasetName: null,
        regionFieldName: null,
        featurePicName: '',
        mapCenter: { x: 126, y: 46 },
        'projectLayerTreeData': [
          {
            name: 'redline',
            label: '生态红线/自然保护区',
            id: '127a43ab-d7f8-45f2-9c42-e6b449a6df6c',
            type: 1
          },
          {
            name: 'waterprotect',
            label: '水源地保护区',
            id: '7a7e7449-776a-4ba2-a1e6-9cc0328502e8',
            type: 1
          },
          {
            name: 'landspace',
            label: '国土空间规划',
            id: 'c91c7d8b-d617-4d16-99d7-ddbaa89174ac',
            type: 1
          }
        ]
      },
      showBtn: {
        measureLength: true,
        measureArea: true,
        drawPlotting: false,
        localPosition: true,
        rightbtns: 'allClose',
        clearSelected: true
      },
      mcShow: {
        catalog: false,
        loPosition: false,
        drawPlotting: 'allClose',//标绘
        showStatics: {
          redline: false,
          waterprotect: false
        }
      },
      mmConfig: {
        'extent': [110, 42, 140, 53],
        'mapRegion': {
          f_levels: 1,
          f_regioncode: 'f_regioncode',
          f_userid: -1,
          f_username: 'f_username',
          f_name: '',
          prjcode: 'EPSG:4490',
          userPrjCode: 'EPSG:4490',
          f_xmax: 140,
          f_xmin: 110,
          f_ymax: 53,
          f_ymin: 42,
          geomwkt: ''
        },
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        mcShow:{mapSourceLoad:false},
      }
    }
  },
  props: {
    proFeatures: {
      type: Array,
      default() {
        return []
      }
    }

  },
  computed: {
    setVisible: function() {
      return function(arg1) {
        let result = false
        for (let i = 0; i < arg1.length; i++) {
          if (arg1[i] === true) {
            result = true
          }
        }
        return result
      }
    }
  },
  created() {
  },
  mounted() {
    this.InitView()
    this.InitMap()
    this.InitMapSource()
    this.mmConfig.mcShow.mapSourceLoad = true;
  },
  methods: {
    ZoomToOverSource() {
      var that = this
      if (that.overSource == null) {
        return
      }
      if (that.overSource.getFeatures().length == 0) {
        return
      }
      var extent = that.overSource.getExtent()
      var extentObj = {
        center: { x: (extent[0] + extent[2]) / 2, y: (extent[1] + extent[3]) / 2 },
        width: Math.abs(extent[2] - extent[0]),
        height: Math.abs(extent[3] - extent[1])
      }
      var tol = that.tol
      if (extentObj.width < tol && extentObj.height < tol) {
        extent = [extentObj.center.x - tol / 2, extentObj.center.y - tol / 2, extentObj.center.x + tol / 2, extentObj.center.y + tol / 2]
      }
      that.map.getView().fit(extent, { size: that.map.getSize(), padding: [100, 100, 100, 100] })
    },
    ZoomToExtent() {
      let that = this
      that.overSource.clear()
      that.overSource.addFeatures(that.project.feature)
      that.ZoomToOverSource()
    },
    //地图按钮点击事件
    mapBtnIClick(e) {
      let that = this
      let type = e.currentTarget.getAttribute('type')
      switch (type) {
        case 'measureLength'://画线
          that.AddMeasureInteraction('LineString')
          break
        case 'measureArea'://画面
          that.AddMeasureInteraction('Polygon')
          break
        case 'drawPlotting'://标绘
          that.map.removeInteraction(that.measure)
          that.mcShow.drawPlotting = 'drawPlotting'
          break
        case 'clearSelected':
          globalmf.clearLayerByName(that.map, 'xzqRegionLayer') //why20211111
          globalmf.removeAllDrawInteractions(that.map)
          globalmf.removeAllSnapInteractions(that.map)
          globalmf.clearSelectedFeature(that.map, that.overSource)
          break
      }
    },
    /*
   * 添加量测事件
   * @param {type} type
   * @return {undefined}
   */
    AddMeasureInteraction: function(type) {
      let that = this
      that.map.removeInteraction(that.measure)
      that.map.removeInteraction(that.snap)
      that.measure = new ol.interaction.Draw({
        source: that.overSource,
        type: type,
        snapTolerance: 20,
        style: new ol.style.Style({
          fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.2)' }),
          stroke: new ol.style.Stroke({
            color: 'rgba(0, 0, 0, 0.5)',
            lineDash: [10, 10],
            width: 2
          }),
          image: new ol.style.Circle({
            radius: 5,
            stroke: new ol.style.Stroke({ color: 'rgba(0, 0, 0, 0.7)' }),
            fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.2)' })
          })
        })
      })
      that.map.addInteraction(that.measure)
      let snap = new ol.interaction.Snap({
        source: that.overSource
      })
      that.map.addInteraction(snap)
      that.CreateMeasureTooltip()
      let listener
      that.measure.on('drawstart', function(evt) {
        that.sketch = evt.feature
        let tooltipCoord = evt.coordinate
        listener = that.sketch.getGeometry().on('change', function(evt) {
          if (that.sketch != null) {
            let geom = evt.target
            let output
            if (geom instanceof ol.geom.Polygon) {
              output = that.FormatArea(geom)
              tooltipCoord = geom.getInteriorPoint().getCoordinates()
              that.measureTooltipElement.innerHTML = output
              that.measureTooltip.setPosition(tooltipCoord)
            } else if (geom instanceof ol.geom.LineString) {
              output = that.FormatLength(geom)
              tooltipCoord = geom.getLastCoordinate()
              that.measureTooltipElement.innerHTML = output
              that.measureTooltip.setPosition(tooltipCoord)
            }
          }
        })
      }, this)
      that.measure.on('drawend', function() {
        that.measureTooltipElement.className = 'tooltip tooltip-static'
        that.measureTooltip.setOffset([0, -7])
        that.sketch = null
        that.measureTooltipElement = null
        that.CreateMeasureTooltip()
        ol.Observable.unByKey(listener)
      }, this)
    },
    CreateMeasureTooltip: function() {
      let that = this
      if (that.measureTooltipElement) {
        that.measureTooltipElement.parentNode.removeChild(that.measureTooltipElement)
      }
      that.measureTooltipElement = document.createElement('div')
      that.measureTooltipElement.className = 'tooltip tooltip-measure'
      that.measureTooltip = new ol.Overlay({
        id: 'measureResult',
        element: that.measureTooltipElement,
        offset: [0, -15],
        positioning: 'bottom-center'
      })
      that.map.addOverlay(that.measureTooltip)
    },
    //距离测量用到的
    FormatLength: function(line) {
      let that = this
      let output
      let length = ol.sphere.getLength(line, {
        projection: that.map.getView().getProjection().getCode(),
        radius: 6378137
      })
      if (length > 100) {
        output = (Math.round(length / 1000 * 100) / 100) +
          ' ' + 'km'
      } else {
        output = (Math.round(length * 100) / 100) +
          ' ' + 'm'
      }
      return output
    },
    //面积测量用到的
    FormatArea: function(polygon) {
      let that = this
      let area = ol.sphere.getArea(polygon, {
        projection: that.map.getView().getProjection().getCode(),
        radius: 6378137
      })
      let output
      if (area > 10000) {
        output = (Math.round(area / 1000000 * 100) / 100) +
          ' ' + 'km<sup>2</sup>'
      } else {
        output = (Math.round(area * 100) / 100) +
          ' ' + 'm<sup>2</sup>'
      }
      return output
    },
    localPositionClickSpan() {//输入坐标后，点击定位，执行函数
      var lon = parseFloat(this.$refs.lp_coordinateX_text.value)
      var lat = parseFloat(this.$refs.lp_coordinateY_text.value)
      if (lon <= 180 && lon >= -180 && lat <= 90 && lat >= -90) {
        let geom = new ol.geom.Point([lon, lat])
        let feature = new ol.Feature({
          geometry: geom
        })
        this.overSource.addFeature(feature)
        this.map.getView().fit(geom, { maxZoom: 12 })
      } else {
        alert('坐标范围错误')
        return
      }
    },
    localPositionCloseSpan() {
      this.mcShow.loPosition = false
    },
    ChangeMenuCss(e) {
      let that = this
      let type = e.currentTarget.getAttribute('type')
      if (this.showBtn.rightbtns === type) {
        this.showBtn.rightbtns = 'allClose'
      } else {
        this.showBtn.rightbtns = type
      }
    },
    InitMapSource() {
      let that = this
      that.overSource = new ol.source.Vector({ crossOrigin: 'anonymous', wrapX: false })
      that.overVector = new ol.layer.Vector({
        source: that.overSource,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(100,100,100,0.36)'
          }),
          stroke: new ol.style.Stroke({
            color: '#ffcc00', //'#d74a4a',#ffcc33
            width: 2
          }),
          image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
              color: '#005aff'
            })
          })
        })
      })
      that.map.addLayer(that.overVector)
      that.overVector.setZIndex(9999)
    },
    InitMap() {
      var that = this
      that.map = new ol.Map({
        target: 'proMap',
        controls: ol.control.defaults({
          attributionOptions: ({
            collapsible: false//2022年2月28日 LQ 很诡异，map的一堆control初始都有问题。
          })
        }).extend([
          new ol.control.MousePosition({//2022年2月28日 LQ，这两个Control位置有问题，等到有空的时候看看
            coordinateFormat: ol.coordinate.createStringXY(4),
            className: 'custom-mouse-position',
            target: document.getElementById('mouse-position'),
            undefinedHTML: '&nbsp;'
          }),
          new ol.control.ScaleLine()//2022年2月28日 LQ，这两个Control位置有问题，等到有空的时候看看
        ]),
        view: that.viewNow
      })
    },
    InitView() {
      var that = this
      //2021年10月15日 LQ  3857的view
      var resolutions3857 = []
      var matrixIds3857 = new Array(22)
      for (var z = 0; z < 22; ++z) {
        resolutions3857[z] = 156543.033928041 / Math.pow(2, z)
        matrixIds3857[z] = z
      }
      var envelope3857 = {}
      envelope3857.left = -20037508.3427892
      envelope3857.bottom = -20037508.3427892
      envelope3857.right = 20037508.3427892
      envelope3857.top = 20037508.3427892
      that.prj3857 = ol.proj.get('EPSG:3857')
      that.prj3857.setExtent([envelope3857.left, envelope3857.bottom, envelope3857.right, envelope3857.top])
      that.prj3857.setWorldExtent([envelope3857.left, envelope3857.bottom, envelope3857.right, envelope3857.top])
      that.view3857 = new ol.View({
        projection: that.prj3857,
        resolutions: resolutions3857,
        center: [14357455, 5806768],
        zoom: 9
      })
      that.view3857.setMinZoom(9) //最小放大到9级，8级的话 平面坐标显示就有问题了
      //2021年10月15日 LQ  4490的view
      var topResolution = 360.0 / 512
      var resolutions = []
      for (var zoom = 0; zoom < 22; zoom++) {
        resolutions.push(topResolution / Math.pow(2, zoom))
      }
      proj4.defs('EPSG:4490', '+proj=longlat +ellps=GRS80 +no_defs')
      that.prj = ol.proj.get(that.prjCodeStr)
      var envelope = {}
      envelope.left = -180
      envelope.bottom = -90
      envelope.right = 180
      envelope.top = 90
      that.prj.setExtent([envelope.left, envelope.bottom, envelope.right, envelope.top])
      that.prj.setWorldExtent([envelope.left, envelope.bottom, envelope.right, envelope.top])
      that.view4490 = new ol.View({
        projection: that.prj, //ol.proj.get("EPSG:4326"),
        resolutions: resolutions,
        center: [that.config.mapCenter.x, that.config.mapCenter.y],
        zoom: 6
      })
      //按照用户选择投影坐标系
      that.viewNow = that.view4490
      /*if (that.mmConfig.mapRegion.userPrjCode == "EPSG:3857") {
    that.viewNow = that.view3857;
    that.mapTemplate.proj = '3857';//绑定了投影对应的radio。
  } else {
    that.viewNow = that.view4490;
    that.mapTemplate.proj = '4490';
  }*/
    },
    //添加features到地图
    AddFeaturesToOverSource(features) {
      let that = this
      that.overSource.clear()
      if (features.length === 0) {
        this.$message({
          message: '该项目没有空间位置信息。',
          type: 'warning'
        })
        return
      }
      that.overSource.addFeatures(features)
      that.ZoomToOverSource()
    }
  }
}
</script>

<style scoped>
.addressDetail {
  margin-top: 10px;
}

.mouse-position {
  position: absolute;
  bottom: 45px;
}

.projectForm {
  position: absolute;
  left: 0;
  width: 50%;
  height: 100%;
}

#proMap {
  /*position: absolute;*/
  /*right:0;*/
  width: 100%;
  height: 100%;
}

/*地图操作*/
.layer-switch {
  right: 8px;
  bottom: 20px;
  display: flex;
  background-color: rgb(186, 238, 186) !important;
  padding: 3px 3px 0px 3px;
  height: 30px;
  /* margin-bottom: 13px; */
  font-size: 16px;
  position: absolute;
  z-index: 1;
  border-radius: 4px;
  box-shadow: #000 0px 0px 5px;
}

.ol-scale-line {
  bottom: 25px !important;
}

.map-btns {
  position: absolute;
  z-index: 1;
  right: 8px;
  bottom: 70px;
  display: block;
  padding: 3px 3px 0px 3px;
  background-color: rgba(255, 255, 255, .5);
  border-radius: 4px;
}

.map-btn {
  height: 30px;
  margin-bottom: 13px;
  font-size: 16px;
  line-height: 1.5;
}

.map-btns i {
  color: #ffffffeb;
  cursor: pointer;
  width: 25px;
  height: 25px;
  border-radius: 4px;
  display: inline;
  padding: 4px;
  background-color: #008680;
  border-color: #ccc;
}

.map-btn .sub-menu {
  right: 31px;
  display: flex;
  background-color: rgba(255, 255, 255, .5);
  position: absolute;
  margin-top: -25px;
  height: 46px;
  box-shadow: #000 0px 0px 5px;
  border-radius: 4px;
  padding: 4px;
}

.map-btn label {
  display: block;
  color: #000000;
  font-weight: normal;
  font-size: 6px;
  text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}

.sub-menu .map-btn {
  margin: 0px 2px;
}

.localPosition-popup {
  margin-left: -266px;
  margin-top: -50px;
  background-color: rgba(255, 255, 255, .5);
  width: 250px;
  height: 110px;
  padding: 10px;
  box-sizing: border-box;
  text-align: center;
  line-height: 33px;
}

.localPosition-popup span[type=position] {
  background-color: #008680;
  color: #fff;
  border-radius: 5px;
  padding: 2px 10px;
  line-height: 20px;
  cursor: pointer;
  margin: 0 10px 0 10px;
}

.catalog-div {
  width: auto !important;
  height: auto !important;
  /* bottom: 160px;*/
  padding-bottom: 12px;
  margin-left: 34px;
  border-radius: 5px;
  max-width: 300px;
  /*min-width: 200px;*/
  position: absolute;
  overflow: auto;
  z-index: 100;
  top: 12px;
  background-color: #004a47ab;
}
</style>
